#include "stdafx.h"
#include "ServerApp.h"
#include "HCM/AssemblyRegistration.h"

using namespace Hiranipra;
using namespace Hiranipra::HCM;
using namespace Hiranipra::Platform;
using namespace Hiranipra::Platform::IO;
using namespace Hiranipra::Server;

ServerApp::ServerApp()
{
}

ServerApp::~ServerApp()
{
	RELEASE( _app );
}

bool ServerApp::RegisterAssembly( wstring path )
{
	return HCMRegisterAssembly( _hcmRegistry, path );
}

class ServerApp::NetworkRunner : public Runnable, HANDLES( NetEvent )
{
public:
	ServerApp*			App;
	bool				Stop;

	NetworkRunner( ServerApp* app ) :
		App( app ), Stop( false )
	{
	}
	
	void run()
	{
		IApplication* app = App->GetApplication();

		NetServer* netServer = new NetServer();
		App->_netServer = netServer;
		netServer->EventSource.Add( this );

		Address address( Address::Any, 9800 );
		netServer->Listen( address, 32 );

		while( this->Stop == false )
		{
			if( netServer->Poll( 150 ) == false )
			{
				// Timed out? No packets?
			}
		}

		RELEASE( netServer );
	}

	DEFINE_HANDLER( ServerApp::NetworkRunner, NetEvent )
	{
		switch( ev.Name )
		{
		case NetEvent::Connected:
			break;
		case NetEvent::Disconnected:
			break;
		case NetEvent::Received:
			break;
		}
	}
};

int ServerApp::Start( wstring appPath, vector<wstring> args )
{
	_app = _hcmRegistry.AllocateDefault<IApplication>( COMPONENT_TYPE( IApplication ) );
	_fs = _hcmRegistry.AllocateDefault<IFileSystem>( COMPONENT_TYPE( IFileSystem ) );

	_fs->Setup( appPath );

	NetworkRunner* netRunner = new NetworkRunner( this );
	Task netRunnerTask( netRunner );
	Thread netRunnerThread( netRunnerTask );

	netRunnerThread.wait();

	return 0;
}
